package com.example.zzx.dovebook.utils

import android.content.Context
import com.example.baselibrary.commonutil.FormatUtil
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream

object FileController {

    private const val TAG = "FileController"

    private const val TEMP_COVER_DIR_NAME = "Book/TempCover"
    private const val CACHE_NET_COVER_DIA_NAME = "Book/NetCover"
    private const val TEMP_COVER_FILE_NAME = "temp_cover_image"

    const val COVER_FILE_PROVIDER_AUTHORITIES = "com.example.zzx.dovebook.file.provider"

    fun getTempCoverPath(context: Context): String {
        val tempCoverDir = context.getExternalFilesDir(TEMP_COVER_DIR_NAME)
        if (!tempCoverDir.exists()) {
            tempCoverDir.mkdirs()
        }
        val tempCoverFile = File(tempCoverDir, "${TEMP_COVER_FILE_NAME}_${FormatUtil
            .dateFormatWithLine(System.currentTimeMillis())}")
        return tempCoverFile.absolutePath
    }

    fun saveBookCover(context: Context, file: File): String? {
        val netCoverDir = context.getExternalFilesDir(CACHE_NET_COVER_DIA_NAME)
        if (!netCoverDir.exists()) {
            netCoverDir.mkdirs()
        }
        val coverFile = File(netCoverDir, file.name)
        var path = coverFile.absolutePath
        if (coverFile.exists()) {
            return path
        }
        var fis: FileInputStream? = null
        var fos: FileOutputStream? = null
        try {
            fis = FileInputStream(file)
            fos = FileOutputStream(coverFile)
            var buffer = ByteArray(1024)
            var len: Int
            while (fis.read(buffer).apply {
                    len = this
                } != -1) {
                fos.write(buffer, 0, len)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            path = null
        } finally {
            fis?.apply {
                close()
            }
            fos?.apply {
                close()
            }
        }
        return path
    }


}